#!/usr/bin/env python3
"""
OCIO Definition Generator

This script reads an OCIO configuration file and generates a Python
file with static lists of color spaces for use in ComfyUI nodes.
"""

import os
try:
    import PyOpenColorIO as ocio
except ImportError:
    print("PyOpenColorIO is required to run this script. Please install it.")
    print("Example: pip install opencolorio")
    exit(1)

def generate_defs(config_path: str, output_path: str):
    """
    Reads an OCIO config and writes a Python file with the color spaces.
    """
    if not os.path.exists(config_path):
        print(f"Error: Config file not found at '{config_path}'")
        return

    try:
        config = ocio.Config.CreateFromFile(config_path)
        color_spaces = [cs.getName() for cs in config.getColorSpaces()]
    except ocio.Exception as e:
        print(f"Error reading OCIO config: {e}")
        return

    with open(output_path, "w") as f:
        f.write('"""\n')
        f.write('DO NOT EDIT THIS FILE DIRECTLY.\n')
        f.write('This file is auto-generated by generate_ocio_defs.py.\n')
        f.write('"""\n\n')
        f.write('OCIO_SPACES = [\n')
        for space in sorted(color_spaces):
            f.write(f'    "{space}",\n')
        f.write(']\n')

    print(f"Successfully generated '{output_path}' with {len(color_spaces)} color spaces.")

if __name__ == "__main__":
    # Get the path to the bundled OCIO config
    ocio_dir = os.path.join(os.path.dirname(__file__), "ocio")
    default_config = os.path.join(ocio_dir, "config.ocio")
    
    # Define the output path for the definitions file
    nodes_dir = os.path.join(os.path.dirname(__file__), "nodes")
    output_file = os.path.join(nodes_dir, "ocio_defs.py")
    
    print(f"Using OCIO config: {default_config}")
    generate_defs(default_config, output_file)
